package org.lq.us.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.tools.sjavac.Log;

import lombok.extern.log4j.Log4j;

/**
 * Servlet Filter implementation class CharSetEncodingFilter
 */
@WebFilter("/*")
@Log4j
public class CharSetEncodingFilter implements Filter {
	private ServletContext context = null;
    /**
     * Default constructor. 
     */
    public CharSetEncodingFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		String path = req.getServletPath();
		String ext = path.substring(path.lastIndexOf(".")+1);
		if(!"js".equals(ext) && !"css".equals(ext)) {
			String encoding = context.getInitParameter("encoding");
			log.info("项目字符集 : "+encoding);
			req.setCharacterEncoding(encoding);
			resp.setContentType("text/html;charset="+encoding);
		}
		
		
		// pass the request along the filter chain
		chain.doFilter(req, resp);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		context = fConfig.getServletContext();
	}

}
